package com.itwc.websocketdemo.controller;


import com.itwc.websocketdemo.entity.SysUser;
import com.itwc.websocketdemo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/users")
public class UserController {

    
    @Autowired
    private UserService userService;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> loginData) {
        Map<String, Object> result = new HashMap<>();
        try {
            String userName = loginData.get("userName");
            String password = loginData.get("password");
            
            if (userName == null || password == null) {
                result.put("success", false);
                result.put("message", "用户名和密码不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            SysUser user = userService.login(userName, password);
            if (user == null) {
                result.put("success", false);
                result.put("message", "用户名或密码错误");
                return ResponseEntity.status(401).body(result);
            }
            
            // 移除密码字段
            user.setPassword(null);
            
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("data", user);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("用户登录失败", e);
            result.put("success", false);
            result.put("message", "登录失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
    
    /**
     * 获取用户信息
     */
    @GetMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> getUserInfo(@PathVariable Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            SysUser user = userService.getUserById(userId);
            if (user == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return ResponseEntity.status(404).body(result);
            }
            
            // 移除密码字段
            user.setPassword(null);
            
            result.put("success", true);
            result.put("data", user);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            result.put("success", false);
            result.put("message", "获取用户信息失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
}